package git.soulbgm.controller;

import org.apache.commons.compress.utils.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 文件控制器
 *
 * @author SoulBGM
 * @date 2022/08/08 14:10
 */
@RestController
@RequestMapping("file")
public class FileController {

    private static final String BASE_URL = "/file";

    @GetMapping("/img/**")
    public void get(HttpServletResponse response, HttpServletRequest request) throws IOException {
        response.setContentType("image/jpeg");
        String uri = request.getRequestURI();
        String path = uri.substring(uri.indexOf(BASE_URL) + BASE_URL.length());
        ServletOutputStream outputStream = response.getOutputStream();
        try (FileInputStream input = new FileInputStream(path);) {
            outputStream.write(IOUtils.toByteArray(input));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
